package com.linghang.jdbc;

import java.sql.*;
import java.util.List;

/**
 * @author qyyzxty@icloud.com
 * @data 2021/4/28
 * JDBC工具类
 **/
public class JDBCUtil {
    //用户名
    private static final String USERNAME = "root";
    //密码
    private static final String PASSWORD = "Flzx3qcYsyhl9t";
    //连接URL
    private static final String URL = "jdbc:mysql://8.131.57.6:3306/xty?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=Asia/Shanghai";
    //连接
    private static Connection connection = null;

    //执行查询语句
    public static ResultSet executeQuery(String sql, List<String> args) throws SQLException {
        if (connection == null) {
            //获取连接
            connection = DriverManager.getConnection(URL, USERNAME, PASSWORD);
        }
        try {
            //加载驱动类
            Class.forName("com.mysql.cj.jdbc.Driver");
            //获取准备状态
            PreparedStatement statement = connection.prepareStatement(sql);
            //遍历填入参数
            int i = 0;
            for (String arg : args) {
                statement.setString(++i, arg);
            }
            //返回结果集
            return statement.executeQuery();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    //执行更新删除插入语句
    public static int executeUpdate(String sql, List<String> args) throws SQLException {
        if (connection == null) {
            //获取连接
            connection = DriverManager.getConnection(URL, USERNAME, PASSWORD);
        }
        try {
            //加载驱动类
            Class.forName("com.mysql.cj.jdbc.Driver");
            //获取准备状态
            PreparedStatement statement = connection.prepareStatement(sql);
            //遍历填入参数
            int i = 0;
            for (String arg : args) {
                statement.setString(i, arg);
            }
            //返回结果集
            return statement.executeUpdate();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return -1;
    }
}
